#include <stdio.h>
#include <iostream>
#include <curl/curl.h>
#include <string>
#include <stdlib.h>
#include <boost/algorithm/string.hpp>
#include "sslclient.h"

#include <fstream>
#include <string>
#include <iostream>
#include "http_sanitize.h"

static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
	((std::string*)userp)->append((char*)contents, size * nmemb);
	return size * nmemb;
}

std::string sslclient::connect(http_sanitize & http)
{
	CURL *curl;
	CURLcode res;
	std::string postData;
	curl_global_init(CURL_GLOBAL_DEFAULT);

	curl = curl_easy_init();
	std::string readBuffer;
	std::string responseBody;
	if(curl)
	{

		struct curl_slist *chunk = NULL;

		http_sanitize::Request request = http.getRequestHeaderFromClient();
//		request.http_header_row;

		for(http_sanitize::StringList::const_iterator row = request.http_header_row.begin() ; row != request.http_header_row.end(); ++row)
		{
			std::string rowData = (*row);
			if( ! rowData.empty())
				chunk = curl_slist_append(chunk, rowData.c_str());
		}

		res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
		curl_easy_setopt(curl, CURLOPT_URL, request.url.c_str());
		std::cout << "url=" << request.url << std::endl;

		postData = http.getRequestBodyFromClient();
		if( ! postData.empty())
		{
			curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, postData.size());
			curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData.c_str());
		}

		curl_easy_setopt(curl, CURLOPT_HEADERDATA, &readBuffer);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseBody);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0);
		curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
		curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 4);
		//curl_easy_setopt(curl, CURLOPT_SSL_CIPHER_LIST, "AES128-SHA:+RC4-SHA:+DHE-RSA-AES128-SHA:-RC4-MD5:-EXP-RC4-MD5");
		curl_easy_setopt(curl, CURLOPT_SSL_CIPHER_LIST, "AES128-SHA:AES256-SHA:RC4-MD5");
//    curl_easy_setopt(curl, CURLOPT_SSL_CIPHER_LIST, "RC4-SHA");
		if(CURLE_OK != curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_0))
			std::cout << "SSL not supported" << std::endl;


		res = curl_easy_perform(curl);

		if(res != CURLE_OK)
		{
			fprintf(stderr, "curl_easy_perform() failed: %s %d url=%s\n", curl_easy_strerror(res), res, request.url.c_str());
		}

		curl_easy_cleanup(curl);
	}


	curl_global_cleanup();
	http.responseHeaderFromServer(readBuffer);
	http.responseBodyFromServer(responseBody);

	return readBuffer;
}

